package com.lemon.core.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Collection;

/**
 * @author 李猛
 * @datetime 2023/12/21 10:15
 * @description 类对象
 */
@Slf4j
public class EasyExcelUtil {
    /**
     * EasyExcel下载
     *
     * @param response
     * @param tClass
     * @param fileName
     * @param sheet
     * @param data
     * @param <T>
     */
    public static <T> void download(HttpServletResponse response, Class<T> tClass, String fileName, String sheet, Collection<T> data) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String filename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", filename + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        try {
            EasyExcel.write(response.getOutputStream(), tClass).sheet(sheet).doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下载
     *
     * @param data
     * @param <T>
     */
    public static <T> void download(Collection<T> data, Class<T> tClass) {
        HttpServletResponse response = SpringUtil.getBean(HttpServletResponse.class);
        String fileName = LocalDateTime.now().format(LocalDateUtil.dateFormatter5);
        String sheet = LocalDateTime.now().format(LocalDateUtil.dateFormatter6);
        download(response, tClass, fileName, sheet, data);
    }
}
